package com.czy.daishusys.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.login.LoginActivity;
import com.czy.daishusys.utils.tiputils.MToast;
import com.hyphenate.chat.EMClient;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.czy.daishusys.application.CzyApplication.mContext;
import static com.czy.daishusys.global.Constants.IM_IS_SHOEW_DIALOG;

/**
 * Created by wangyang on 2016/5/23.
 * 手机工具类
 */
public class PhoneUtils {

    /**
     * 没有网络
     */
    public static final int NETWORKTYPE_INVALID = 0;
    /**
     * wap网络
     */
    public static final int NETWORKTYPE_WAP = 1;
    /**
     * 2G网络
     */
    public static final int NETWORKTYPE_2G = 2;
    /**
     * 3G和3G以上网络，或统称为快速网络
     */
    public static final int NETWORKTYPE_3G = 3;
    /**
     * wifi网络
     */
    public static final int NETWORKTYPE_WIFI = 4;

    public static int mNetWorkType = 1;

    public static long timeDifference = 0;

    /**
     * 判断手机联网状态
     *
     * @param context
     * @return
     */
    public static boolean checkNetwork(Context context) {
        if (isNetworkConnected(context) == true) {
            //Toast.makeText(context, "当前网络不可用，请设置", Toast.LENGTH_SHORT).show();
            return isWifiConnected(context) == true || isMobileConnected(context) == true;
        } else {
            //Toast.makeText(context, "当前网络不可用，请设置", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 判断是否有链接的网络
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            } else {
                PhoneUtils.ShowToastMessage(context, "网络连接错误!");
            }
        }
        return false;
    }

    /**
     * 描述 判断wifi是否可用
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (info != null) {
                return info.isAvailable();
            }
        }
        return false;
    }

    /**
     * 描述 判断移动网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (info != null) {
                return info.isAvailable();
            }
        }
        return false;
    }

    /**
     * 获取手机屏幕得宽度
     *
     * @param context
     * @return
     */
    public static int getPhoneWidth(Context context) {
        Activity activity = (Activity) context;
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    /**
     * 获取手机屏幕得高度
     *
     * @param context
     * @return
     */
    public static int getPhoneHeight(Context context) {
        Activity activity = (Activity) context;
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }

    public static Point getDeviceSize(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
            point.x = manager.getDefaultDisplay().getWidth();
            point.y = manager.getDefaultDisplay().getHeight();
        } else {
            manager.getDefaultDisplay().getSize(point);
        }
        return point;
    }

    /**
     * 获取状态栏高度＋标题栏高度
     *
     * @param activity
     * @return
     */
    public static int getTopBarHeight(Activity activity) {
        return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
    }


    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
            /*
             * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
             * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
             * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
             */
//        String telRegex = "[1][34758]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "^((13[0-9])|(14[0-9])|(15[^4,\\D])|(1(7|8)[^4,\\D]))\\d{8}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }


    //	验证邮箱格式

    public static boolean isEmail(String email) {

        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        Pattern p = Pattern.compile(str);

        Matcher m = p.matcher(email);

        return m.matches();

    }

    /**
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取app版本号码
     *
     * @param context
     * @return
     */
    public static String getVersion(Context context)//获取版本号
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return 0 + "";
        }
    }

    public static int getVersionCode(Context context)//获取版本号(内部识别号)
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }


    //Pop背景设置
    public static void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        activity.getWindow().setAttributes(lp);
    }

    public static boolean checkLicensePlate(String licensePlate) {
        /*
         车牌号格式：汉字 + A-Z + 5位A-Z或0-9
        （只包括了普通车牌号，教练车和部分部队车等车牌号不包括在内）
         */
        String licensePlateRegex = "[A-Z]{1}[A-Z_0-9]{4}[A-Z_0-9警学]{1}";
        if (TextUtils.isEmpty(licensePlate)) return false;
        else return licensePlate.matches(licensePlateRegex);
    }


    public static void ShowToastMessage(Context context, String str) {
//        UIToast.showBaseToast(context, str, true, UIToast.NONE, UIToast.NONE, null, UIToast.NONE, UIToast.NONE, UIToast.NONE, R.style.AnimationToast);
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
//        MToast.makeTextShort(mContext, "登陆成功", toastConfig).show();
    }


    public static void checkCallPermission(Context mContext, String phoneNumber) {
        Intent intentPhone = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber.replaceAll("转", ";")));
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber.replaceAll("转", ";")));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } else {
//            mContext.startActivity(intentPhone);
        }
    }

    public static String checkResponseFlag(Activity activity, String result) {
        MyLog.i("checkResponseFlag", result);
        String exp = JsonUtil.getJsonValuesString(result, "exp");
        boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
        int errorCode = JsonUtil.getJsonValuesInt(result, "errorCode");
        if (flag) {
            return JsonUtil.getJsonValuesString(result, "data");
        } else {
            // TODO 检查错误码,如是110 登录超时
            switch (errorCode) {
                case 110:
                    try {
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_SESSION_INFO_MODEL);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_USER_INFO_MODEL);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_OWNER_INFO_MODEL);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_ADMIN_INFO_MODEL);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_CHAIN_STORES_MODEL);
                        SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID);
                        ActivityHelper.getInstance().finishAllActivity();
                        UserHelper.getInstance().setUserInfoModel(activity, null);
                        UserHelper.getInstance().setSessionInfoModel(activity, null);
                        UserHelper.getInstance().setOwnerInfoModel(activity, null);
                        UserHelper.getInstance().setmChainStoresList(activity, null);
                        UserHelper.getInstance().setIsLogined(false);
                        EMClient.getInstance().logout(true);
                    } catch (Exception e) {

                    }

                    activity.startActivity(new Intent(activity, LoginActivity.class).putExtra(IM_IS_SHOEW_DIALOG, true));
                    break;
                default:
                    PhoneUtils.ShowToastMessage(activity, TextUtils.isEmpty(exp) ? "连接服务器失败" : exp);
            }
            return null;
        }
    }


    /**
     * 定义script的正则表达式
     */
    private static final String REGEX_SCRIPT = "<script[^>]*?>[\\s\\S]*?<\\/script>";
    /**
     * 定义style的正则表达式
     */
    private static final String REGEX_STYLE = "<style[^>]*?>[\\s\\S]*?<\\/style>";
    /**
     * 定义HTML标签的正则表达式
     */
    private static final String REGEX_HTML = "<[^>]+>";
    /**
     * 定义空格回车换行符
     */
    private static final String REGEX_SPACE = "\\s*|\t|\r|\n";
    private static final String REGEX_SPACE2 = "&emsp;|&thinsp;|&zwnj;|&zwj;|&nbsp;";

    public static String delHTMLTag(String htmlStr) {
        // 过滤script标签
        Pattern p_script = Pattern.compile(REGEX_SCRIPT, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");
        // 过滤style标签
        Pattern p_style = Pattern.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");
        // 过滤html标签
        Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");
        // 过滤空格回车标签
        Pattern p_space = Pattern.compile(REGEX_SPACE, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll("");


        // 过滤空格回车标签
        Pattern p_space2 = Pattern.compile(REGEX_SPACE2, Pattern.CASE_INSENSITIVE);
        Matcher m_space2 = p_space2.matcher(htmlStr);
        htmlStr = m_space2.replaceAll("");

        return htmlStr.trim(); // 返回文本字符串
    }

    public static boolean isEmpty(String string) {
        if (string == null || "".equals(string) || "null".equals(string)) {
            return true;
        }
        return false;
    }

    public static String getString(String string) {
        return string != null ? string : "";
    }

    public static String getString(String string, String defaultString) {
        if ("".equals(string))
            return defaultString;
        return string != null ? string : defaultString;
    }

    public static long getTime() {
        return System.currentTimeMillis() + timeDifference;
    }
}
